package com.hmall.search.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.common.domain.dto.PageDTO;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.service.IItemSearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 搜索服务实现类
 * <p>
 * @author: liuhongjun
 * @since: 2024-05-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ItemSearchServiceImpl implements IItemSearchService {

    private final RestHighLevelClient client;
    private final ItemClient itemClient;

    @Override
    public void save(ItemDTO itemDTO) {
        // 1.将ItemDTO转json
        String doc = JSONUtil.toJsonStr(itemDTO);
        // 2.准备Request对象
        IndexRequest request = new IndexRequest("items").id(itemDTO.getId().toString());
        // 3.准备Json文档
        request.source(doc, XContentType.JSON);
        // 4.发送请求
        try {
            this.client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("商品文档新增异常");
        }
    }

    @Override
    public void update(List<Long> ids) {
        // 1.根据id查询商品信息
        List<ItemDTO> dtoList = this.itemClient.queryItemByIds(ids);
        // 2.创建Request
        BulkRequest request = new BulkRequest("items");
        // 3.遍历商品集合信息
        for (ItemDTO itemDTO : dtoList) {
            // 3.1.将ItemDTO转json
            String doc = JSONUtil.toJsonStr(itemDTO);
            // 3.2.添加文档信息
            request.add(new IndexRequest()
                    .id(itemDTO.getId().toString())
                    .source(doc, XContentType.JSON));
        }
        // 4.发送请求
        try {
            this.client.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("批量更新商品文档异常");
        }
    }

    @Override
    public void delete(Long id) {
        // 1.准备Request，两个参数，第一个是索引库名，第二个是文档id
        DeleteRequest request = new DeleteRequest("items", id.toString());
        // 2.发送请求
        try {
            this.client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("商品文档删除异常");
        }
    }

    @Override
    public PageDTO<ItemDTO> search(ItemPageQuery query) {
        // 1.创建Request
        SearchRequest request = new SearchRequest("items");
        // 2、准备DSL
        // 2.1、query
        this.buildBasicQuery(query, request);
        // 2.2.分页
        Integer pageNo = query.getPageNo();
        Integer pageSize = query.getPageSize();
        request.source().from((pageNo - 1) * pageSize).size(pageSize);
        // 2.3.排序
        Boolean isAsc = query.getIsAsc();
        String sortBy = query.getSortBy();
        if (!sortBy.isBlank() && isAsc != null) {
            request.source().sort(sortBy, isAsc ? SortOrder.ASC : SortOrder.DESC);
        }
        try {
            // 3.发送请求
            SearchResponse response = this.client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return this.handleResponse(response);
        } catch (IOException e) {
            log.error("查询文档异常");
        }
        return null;
    }

    @Override
    public Map<String, List<String>> filters(ItemPageQuery query) {
        try {
            // 1、准备Request
            SearchRequest request = new SearchRequest("items");
            // 2、准备DSL
            // 2.1、query
            this.buildBasicQuery(query, request);
            // 2.2、设置size
            request.source().size(0);
            // 2.3、聚合
            this.buildAggregation(request);
            // 3、发送请求
            SearchResponse response = this.client.search(request, RequestOptions.DEFAULT);
            // 4、解析结果
            Map<String, List<String>> result = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            //4.1、根据分类名称，获取分类结果
            List<String> categoryList = this.getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            //4.2、根据品牌名称，获取品牌结果
            List<String> brandList = this.getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            log.debug("聚合结果：{}", result);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * TODO 部署环境以及测试
     * @param prefix
     * @return
     */
    @Override
    public List<String> suggestions(String prefix) {
        try {
            // 1、准备Request
            SearchRequest request = new SearchRequest("items");
            // 2、准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "mySuggestions",
                    SuggestBuilders
                            .completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3、发送请求
            SearchResponse response = this.client.search(request, RequestOptions.DEFAULT);
            // 4、解析响应
            Suggest suggest = response.getSuggest();
            // 4.1、根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("mySuggestions");
            // 4.2、获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3、遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(20));
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20));
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 1、根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        // 2、获取buckets
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        // 3、遍历
        List<String> list = new ArrayList<>(buckets.size());
        for (Terms.Bucket bucket : buckets) {
            // 4、获取key
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    public void buildBasicQuery(ItemPageQuery query, SearchRequest request) {
        // 1、构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key = query.getKey();
        if (key == null || key.isEmpty()) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("name", key));
        }
        //分类条件
        if (query.getCategory() != null && !query.getCategory().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("category", query.getCategory()));
        }
        //品牌条件
        if (query.getBrand() != null && !query.getBrand().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("brand", query.getBrand()));
        }
        //价格范围
        Integer maxPrice = query.getMaxPrice();
        Integer minPrice = query.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(minPrice)
                    .lte(maxPrice));
        }
        // 2、高亮查询
        request.source().highlighter(
                SearchSourceBuilder.highlight()
                        .field("name")
                        .preTags("<strong style=\"color:#FF007F;\">")
                        .postTags("</strong>"));
        // 3、算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        //原始查询，相关性算分的查询
                        boolQuery,
                        //function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                //其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        //过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        //算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        }
                        //设置boost_mode为MULTIPLY
                ).boostMode(CombineFunction.MULTIPLY);
        //放入source
        request.source().query(functionScoreQuery);
    }

    private PageDTO<ItemDTO> handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 2.遍历结果数组
        SearchHit[] hits = searchHits.getHits();
        int count = hits.length;
        // 3.创建数组存放查询的商品信息
        List<ItemDTO> itemList = new ArrayList<>(count);
        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化文档为商品
            ItemDTO item = JSONUtil.toBean(source, ItemDTO.class);
            // 5.高亮信息输出
            Map<String, HighlightField> hfs = hit.getHighlightFields();
            if (MapUtil.isNotEmpty(hfs)) {
                HighlightField hf = hfs.get("name");
                if (ObjectUtil.isNotEmpty(hf)) {
                    String hfName = hf.getFragments()[0].toString();
                    item.setName(hfName);
                }
            }
            // 6.添加商品信息到数组
            itemList.add(item);
        }
        PageDTO<ItemDTO> page = new PageDTO<>();
        long pages = count == 0 ? 0 : (long) Math.ceil(NumberUtil.div(total, count));
        page.setPages(pages);
        page.setTotal(total);
        page.setList(itemList);
        return page;
    }

}
